from forum import forum_bp
from decoraters import isloginin,isrgroup
from formodle import CreateForum
from flask import redirect,request,render_template,flash,url_for,g
from models import Forumq
from exts import db
from toolfunc import flash_form_error

@forum_bp.route('/createforum_<int:poid>',methods=["GET",'POST'])
@isrgroup(6)
@isloginin
def createforum(poid):
    form=CreateForum()
    if request.method=="GET":  
        return render_template("createforum.html",form=form)
    if request.method=="POST":
        if form.validate_on_submit:
            forum=Forumq.query.filter(Forumq.fo_id==poid).first()
            if forum is None:
                flash("父论坛不存在！")
                return redirect(url_for("root.index"))

            fo_name=request.form.get("fo_name")
            if Forumq.query.filter(Forumq.fo_name==fo_name).first() is not None:
                flash("该论坛名已存在")
                return redirect(url_for("root.index"))
            fo_decript=request.form.get("fo_descr")
            if fo_decript is None:
                newobj=Forumq(fo_name=fo_name,fo_parent_id=poid,u_id=g.uid)
            newobj=Forumq(fo_name=fo_name,fo_parent_id=poid,fo_descript=fo_decript,u_id=g.uid)
            db.session.add(newobj)
            db.session.commit()
            flash("创建成功！")
            return redirect(url_for("root.index"))
        else:
            flash_form_error(form=form)
            return redirect(url_for("root.index"))

@forum_bp.route('/list_<int:poid>')
@isloginin
def forumlist(poid):
    todict=request.args.to_dict()
    page=todict.get('page')
    forum=Forumq.query.filter(Forumq.fo_parent_id==poid)
    if forum.first() is None:
        flash("暂无子论坛")
        #return redirect(url_for("forum.forumlist",poid=1))
    if page is None:
        aims=Forumq.query.filter(Forumq.fo_parent_id==poid).limit(20)
    else:
        aims=Forumq.query.filter(Forumq.fo_parent_id==poid).limit(20).offset(20*(int(page)-1))
    return render_template("forumlist.html",aims=aims,poid=poid)